use crate::{
    common::AppError,
    model::entity::User,
    model::form::{AuthResponse, LoginUser},
    repository::user_repository,
    service::{self, auth::create_jwt},
};
use axum::{
    extract::{Extension, Json},
    response::Json as JsonResponse,
};
use sqlx::PgPool;

pub async fn login_handler(
    Extension(pool): Extension<PgPool>,
    Json(payload): Json<LoginUser>,
) -> Result<JsonResponse<AuthResponse>, AppError> {
    let user = user_repository::find_user_by_email(&pool, &payload.email).await?;

    let is_valid = service::auth::verify_password(&payload.password, &user.password_hash)?;
    if !is_valid {
        return Err(AppError::Unauthorized);
    }

    let token = create_jwt(user.id)?;
    Ok(JsonResponse(AuthResponse { token, user }))
}

pub async fn get_current_user(
    Extension(pool): Extension<PgPool>,
) -> Result<JsonResponse<User>, AppError> {
    // Ok(JsonResponse(user))

    let uuid_str = "123e4567-e89b-12d3-a456-426614174000";
    let id = uuid::Uuid::parse_str(uuid_str)?;
    let u = user_repository::find_user_by_id(&pool, id).await?;
    Ok(JsonResponse(u))
}
